<template>
    <div class="app-container">
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>角色管理</span>
            </div>

            <!-- 查询条件-->
            <el-form :inline="true" :model="selectParam" size="small" class="demo-form-inline">
                <el-form-item label="组 名 称：" class="w5">
                    <el-select v-model="selectParam.groupId" @change="changeGroupId()" class="w3">
                        <el-option label="全部" :value="null"></el-option>
                        <el-option v-for="(item,index) in roleGroupsDropDownBox" :key="index" :label="item.groupName"
                                   :value="item.groupId" style="width: 280px"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="角色名称：" class="w5">
                    <el-select v-model="selectParam.roleId" class="w3">
                        <el-option label="全部" :value="null"></el-option>
                        <el-option v-for="(item,index) in rolesDropDownBox" :key="index" :label="item.roleName"
                                   :value="item.roleId" style="width: 280px"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="float: right;margin-right: 30px">
                    <el-button type="primary" @click="selectParamOnSubmit">查询</el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>


            <!-- 表格-->
            <el-table
                    :data="roles"
                    :span-method="objectSpanMethod"
                    border
                    size="small"
                    :header-cell-style="tableHeaderStyle"
                    style="width: 100%; margin-top: 20px">
                <el-table-column
                        type="index"
                        label="No."
                        align="center"
                        header-align="center"
                        width="50">
                </el-table-column>
                <el-table-column
                        prop="groupName"
                        :show-overflow-tooltip="true"
                        align="center"
                        header-align="center"
                        label="组名称">
                </el-table-column>
                <el-table-column
                        prop="roleName"
                        align="center"
                        :show-overflow-tooltip="true"
                        header-align="center"
                        label="角色名称">
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        align="center"
                        header-align="center"
                        width="300">
                    <template slot-scope="scope">
                        <el-button
                                @click="handleClick(scope.row)"
                                type="text"
                                size="small">查看人员
                        </el-button>
                        <el-button
                                v-if="userButtonIds.indexOf('base.role.power') != -1"
                                @click="handleClickSetPowers(scope.row.roleId)"
                                type="text"
                                size="small">设置权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>


            <!-- 抽屉 查看人员-->
            <el-drawer
                    title="查看人员"
                    :visible.sync="drawerA"
                    :direction="direction"
                    :before-close="handleClose">
                <div class="app-container drawer-div">
                    <el-table
                            :data="userNames"
                            border
                            style="width: 200px; margin: auto"
                            :header-cell-style="tableHeaderStyle"
                            :span-method="objectSpanMethodA">
                        <el-table-column
                                prop="roleName"
                                label="角色名称"
                                width="100"
                                align="center"
                                header-align="center">
                            <template>{{ this.currentRoleName }}</template>
                        </el-table-column>
                        <el-table-column
                                align="center"
                                header-align="center"
                                prop="userNames"
                                label="人员姓名">
                            <template slot-scope="scope">
                                <span v-for="(item,index) in scope.row" :key="index">{{ item }}</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-drawer>


            <!-- 抽屉 设置权限-->
            <el-drawer
                    title="设置权限"
                    size="50%"
                    with-header
                    :visible.sync="drawerB"
                    :direction="direction"
                    :before-close="handleClose">
                <div class="app-container drawer-div">
                    <!-- 表格 设置权限-->
                    <el-table
                            :data="pictures"
                            :span-method="objectSpanMethodSetPower"
                            border
                            size="small"
                            :header-cell-style="tableHeaderStyle"
                            style="width: 800px; margin-top: 20px">
                        <el-table-column
                                label="菜单"
                                header-align="center"
                                width="150">
                            <template slot-scope="scope">
                                <el-checkbox
                                        :indeterminate="moduleIsIndeterminate[scope.$index]"
                                        v-model="moduleIsChoose[scope.$index]"
                                        @change="moduleChange(scope.row.parent.moduleId,moduleIsChoose[scope.$index])">
                                    <span style="font-size: 13px">{{ scope.row.parent.moduleName }}</span>
                                </el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="页面"
                                header-align="center"
                                width="150">
                            <template slot-scope="scope">
                                <el-checkbox
                                        :indeterminate="picIsIndeterminate[scope.$index]"
                                        v-model="picIsChoose[scope.$index]"
                                        @change="pictureChange(scope.row.pictureId,picIsChoose[scope.$index])">
                                    <span style="font-size: 13px">{{ scope.row.pictureName }}</span>
                                </el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column
                                header-align="center"
                                label="按钮">
                            <template slot-scope="scope">
                                <div style="display: flex">
                                    <div v-for="(item,index) in scope.row.children" :key="index" style="width: 88    px">
                                        <el-checkbox
                                                style="margin-right: 20px"
                                                v-model="item.choose"
                                                @change="buttonChange(item)">
                                            <span style="font-size: 13px">{{ item.buttonName }}</span>
                                        </el-checkbox>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>

                </div>
                <div class="demo-drawer__footer" style="z-index: 200">
                    <el-button type="primary" @click="submitRolePowers" style="margin-left: 30px">提交</el-button>
                    <el-button @click="cancelDrawer">取消</el-button>
                </div>
            </el-drawer>
        </el-card>


    </div>
</template>

<script>

import {
    http_role_list,
    http_role_groupNames,
    http_roleNames_groupId,
    http_powers,
    http_role_power_save
} from '@/api/role'
import {Message} from 'element-ui';
import {tableHeaderStyle,} from '@/utils/constant';

const cityOptions = ['上海', '北京', '广州', '深圳'];
export default {
    data() {
        return {
            tableHeaderStyle: tableHeaderStyle,
            userButtonIds: JSON.parse(localStorage.getItem("user")).buttonIds,
            roles: [],
            merges: [],
            groupIds: [],
            rowspan: [],
            mergeIndex: [],
            roleGroupsDropDownBox: [],
            rolesDropDownBox: [],
            selectParam: {
                groupId: null,
                roleId: null,
            },
            currentRoleId: null,

            checkAll: false,
            checkedCities: ['上海', '北京'],
            cities: cityOptions,
            isIndeterminate: false,

            checked: false,
            drawerA: false,
            drawerB: false,
            direction: 'rtl',
            currentRoleName: '',
            userNames: [],
            pictures: [],

            moduleIsChoose: [],
            moduleIsIndeterminate: [],
            picIsChoose: [],
            picIsIndeterminate: [],

            powers: [],
            powerRowIndexs: [],
            powerRowMerges: [],
        };
    },
    created() {
        this.getRoles()
        this.getRoleGroupList()

    },
    methods: {
        getRoles() {
            http_role_list(this.selectParam).then(result => {
                const {data} = result
                this.roles = data
                this.initCellsMerge()
            })
        },
        getRoleGroupList() {
            http_role_groupNames().then(result => {
                const {data} = result
                this.roleGroupsDropDownBox = data
            })
        },
        getRoleNameByGroupId() {
            http_roleNames_groupId(this.selectParam).then(result => {
                const {data} = result
                this.rolesDropDownBox = data
            })
        },
        getPowers() {
            http_powers(this.currentRoleId).then(result => {
                const {data} = result
                this.powers = data
                this.initPowerPowerMergeCells()
                this.initPowers()
            })
        },

        insertRolePowers(powerIds) {
            // console.log("powerIds: ", powerIds)
            let s = ''
            powerIds.forEach((p, i) => {
                s += p
                if (i < powerIds.length - 1) {
                    s += ','
                }
            })

            http_role_power_save(this.currentRoleId, s).then(result => {
                const {message, stateCode} = result
                if (stateCode == '0000') {
                    Message.success(message)
                } else {
                    message.error(message)
                }
            })
        },
        changeGroupId() {
            this.selectParam.roleId = null
            this.getRoleNameByGroupId()
        },
        initCellsMerge() {
            this.groupIds = [...new Set(this.roles.map(r => r.groupId))]
            this.groupIds.forEach(g => {
                let num = 0;
                let i = [];
                this.roles.forEach((r, index) => {
                    if (g == r.groupId) {
                        num++
                        i.push(index)
                    }
                })
                this.rowspan.push(num)
                this.mergeIndex.push(i[0])
            })
        },
        initPowerPowerMergeCells() {
            let powerRowIndexs = [];
            let powerRowMerges = [];
            let rowNum = 0
            this.powers.forEach((p, i) => {
                powerRowIndexs.push(rowNum)
                powerRowMerges.push(p.children.length)
                rowNum = rowNum + p.children.length
            })
            this.powerRowIndexs = powerRowIndexs
            this.powerRowMerges = powerRowMerges
            // console.log("powerRowIndexs:", powerRowIndexs, "powerRowMerges:", powerRowMerges)
        },
        buttonChange(item) {
            this.initPowers()
        },
        submitRolePowers() {
            let powerIds = []
            this.pictures.forEach(pic => {
                pic.children.forEach(button => {
                    if (button.choose == true) {
                        powerIds.push(button.id)
                    }
                })
            })
            // console.log("powerIds: ", powerIds)
            this.insertRolePowers(powerIds)
            this.drawerB = false
        },
        cancelDrawer() {
            this.drawerB = false
        },
        // 页面权限
        pictureChange(id, boo) {
            this.powers.forEach(mod => {
                mod.children.forEach(pic => {
                    if (id == pic.pictureId) {
                        pic.children.forEach(button => {
                            button.choose = boo
                        })
                    }
                })
            })
            this.initPowers()
        },
        moduleChange(id, boo) {
            this.powers.forEach(mod => {
                if (id == mod.moduleId) {
                    mod.children.forEach(pic => {
                        pic.children.forEach(button => {
                            button.choose = boo
                        })
                    })
                }
            })
            this.initPowers()
        },
        resetForm() {
            this.selectParam = {}
            this.getRoles()
        },
        initPowers() {
            this.pictures = []
            this.picIsChoose = []
            this.picIsIndeterminate = []
            this.moduleIsChoose = []
            this.moduleIsIndeterminate = []
            this.powers.forEach(module => {
                let selected = 0
                let indeterminate = 0
                module.children.forEach(pic => {
                    let choose = 0
                    pic.children.forEach(button => {
                        if (button.choose === true) {
                            // console.log("true: ", true)
                            choose++
                        }
                    })
                    let c = false;
                    let i = false;
                    if (choose == pic.children.length) {
                        c = true;
                        i = false;
                    } else if (choose > 0) {
                        c = false;
                        i = true;
                    } else {
                        c = false;
                        i = false;
                    }
                    this.picIsChoose.push(c)
                    this.picIsIndeterminate.push(i)
                    pic.parent = module
                    this.pictures.push(pic)

                    if (c == true) {
                        selected++
                    } else if (i == true) {
                        indeterminate++
                    }
                })
                module.children.forEach(picture => {
                    if (selected == module.children.length) {
                        this.moduleIsChoose.push(true)
                        this.moduleIsIndeterminate.push(false)
                    } else if (selected > 0 || indeterminate > 0) {
                        this.moduleIsChoose.push(false)
                        this.moduleIsIndeterminate.push(true)
                    } else {
                        this.moduleIsChoose.push(false)
                        this.moduleIsIndeterminate.push(false)
                    }
                })
            })
            // console.log("moduleIsChoose: ", this.moduleIsChoose)
            // console.log("moduleIsIndeterminate: ", this.moduleIsIndeterminate)

        },
        handleClick(row) {
            this.currentRoleName = row.roleName
            this.userNames = row.userNames
            this.drawerA = true
            // console.log(this.userNames)
        },
        selectParamOnSubmit() {
            this.getRoles()
        },

        handleClickSetPowers(roleId) {
            this.currentRoleId = roleId
            this.getPowers()
            // console.log(this.powers)
            this.initPowers()
            this.drawerB = true
        },
        handleClose(done) {
            this.drawerA = false
            this.drawerB = false
            this.powers = []
        },
        arraySpanMethod({row, column, rowIndex, columnIndex}) {
            if (rowIndex % 2 === 0) {
                if (columnIndex === 0) {
                    return [1, 2];
                } else if (columnIndex === 1) {
                    return [0, 0];
                }
            }
        },

        objectSpanMethod({row, column, rowIndex, columnIndex}) {
            if (columnIndex == 1) {
                if (this.mergeIndex.concat(rowIndex)) {
                    let index = this.mergeIndex.indexOf(rowIndex)
                    return {
                        rowspan: this.rowspan[index],
                        colspan: 1
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }

            }

        },
        objectSpanMethodA({row, column, rowIndex, columnIndex}) {
            if (columnIndex === 0) {
                if (rowIndex % this.userNames.length === 0) {
                    return {
                        rowspan: this.userNames.length,
                        colspan: 1
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
        },
        objectSpanMethodSetPower({row, column, rowIndex, columnIndex}) {
            if (columnIndex === 0) {
                if (this.powerRowIndexs.concat(rowIndex)) {
                    let index = this.powerRowIndexs.indexOf(rowIndex)
                    return {
                        rowspan: this.powerRowMerges[index],
                        colspan: 1
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
        },
    },

};
</script>

<style>

.box-card {
    width: 100%;
    height: 100%;
}

.w2 {
    width: 200px;
}

.w3 {
    width: 300px;
}

.w4 {
    width: 400px;
}

.w5 {
    width: 500px;
}

.el-drawer__header span:focus {
    outline: 0 !important;
}

.demo-drawer__footer {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background-color: white;
    text-align: center;
}

.drawer-div {
    height: 80vh;
    overflow-y: auto
}
</style>
